package com.h3c.gm.schedule.task

import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.h3c.gm.common.constant.ScheduleURI
import com.h3c.gm.common.utils.SpringContextUtil
import com.h3c.gm.common.utils.UUIDUtils
import com.h3c.gm.entity.DO.BusHostSpecDO
import com.h3c.gm.common.constant.HostOrgkeyPair
import com.h3c.gm.common.utils.HttpUtils
import com.h3c.gm.service.BusHostSpecService
import org.slf4j.Logger
import org.slf4j.LoggerFactory

/**
 * Created by d14287 on 2017/7/7.
 */
class HostTask implements Runnable {

    BusHostSpecService busHostSpecService = SpringContextUtil.getBean(BusHostSpecService.class)
    HostOrgkeyPair hostOrgkeyPair

    @Override
    void run() {
        Optional<JSONArray> optional = HttpUtils.httpGet(hostOrgkeyPair.getProc() + '://' + hostOrgkeyPair.getHost() + ScheduleURI.host_api_uri.replace('{host}', hostOrgkeyPair.getHost()))
        if (!optional.isPresent()) {
            return
        }
        busHostSpecService.deleteByOrgkey(hostOrgkeyPair.name())
        JSONArray arrays = optional.get()
        for (int i = 0; i < arrays.size(); i++) {
            JSONObject object = arrays.getJSONObject(i)
            BusHostSpecDO busHostSpecDO = new BusHostSpecDO()
            busHostSpecDO.setId(UUIDUtils.generateUUID())
            busHostSpecDO.setHostid(object.getString('hostid'))
            busHostSpecDO.setCreatetime(object.getDate('createtime'))
            busHostSpecDO.setCpus(object.getShort('cpus'))
            busHostSpecDO.setRam(object.getLong('ram'))
            busHostSpecDO.setDisk(object.getLong('disk'))
            if ('Y'.equals(object.getString('intrash'))) {
                //Y 在回收站，N不在
                busHostSpecDO.setStatus('RECYCLE')
            } else {
                busHostSpecDO.setStatus(object.getString('status'))
            }
            busHostSpecDO.setOrgkey(hostOrgkeyPair.name())
            busHostSpecService.insert(busHostSpecDO)
        }
    }

    HostTask(HostOrgkeyPair hostOrgkeyPair) {
        this.hostOrgkeyPair = hostOrgkeyPair
    }
}
